package com.sk.bilibili.other;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.sk.api.annotations.Autowired;
import com.sk.api.tool.BindTool;
import com.sk.bilibili.bean.Danmu;
import com.sk.bilibili.callBack.LiveDanmuCallBack;
import com.sk.bilibili.dto.DanmuInfo;

import java.net.URI;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

public class LiveDanmuSocketClient extends WebSocketListener {

    private LiveDanmuCallBack liveDanmuCallBack;
    private Gson gson;
    @Autowired
    OkHttpClient client;
    private WebSocket webSocket;
    private Handler handler=new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            DanmuInfo danmuInfo= (DanmuInfo) msg.obj;
            switch (danmuInfo.getType()){
                case 0:liveDanmuCallBack.online(danmuInfo.getOnline());break;
                case 1:liveDanmuCallBack.danmu(danmuInfo.getDanmu());break;
            }
        }
    };

    public LiveDanmuSocketClient(String url,LiveDanmuCallBack liveDanmuCallBack) {
        this.liveDanmuCallBack=liveDanmuCallBack;
        BindTool.getInstance().bind(this);
        webSocket = client.newWebSocket(new Request.Builder().url(url).build(), this);
        gson=new Gson();
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        Message obtain = Message.obtain();
        obtain.obj=gson.fromJson(text, DanmuInfo.class);
        handler.sendMessage(obtain);
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
        super.onFailure(webSocket, t, response);
        t.printStackTrace();
    }

    public void sendDanmu(Danmu danmu){
        webSocket.send(gson.toJson(danmu));
    }

    public void close() {
        webSocket.close(1000,"正常关闭");
    }

}